import axios from 'axios'
import router from "@/router";
import { message } from "ant-design-vue";
// 创建axios实例
const service = axios.create({
  timeout: 1000000,
  baseURL: process.env.VUE_APP_API_BASE_URL
})

//添加请求拦截器
service.interceptors.request.use(cfg => {
  // console.log(cfg, '请求拦截器!')
  cfg.headers = {
    'Content-Type': 'application/json',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'
  }
  //统一携带token
  const jwt = localStorage.getItem("token");
  if (jwt) {
    //header中加入token
    cfg.headers["Jmt-token"] = jwt;
  }
  return cfg;
}, error => {
  console.log(error, 'sss');
  if (error.response) {
    console.log(error.response.status, 'sss');
    // 判断响应状态码进行对应处理
    if (error.response.status === 401) {
      // 如果是401，跳转到登录页面
      router.push('/login');
    }
  }
  return Promise.reject(error)
})
// 状态异常
const err = error => {
  console.log(error, 'error');
  switch (error.response.status) {
    case 500:
      message.error(error.message);
      break;
    case 404:
      message.error(error.message);
      break;
    case 400:
      message.error(error.message);
      break;
    case 401:
      localStorage.clear();
      router.push("/login");
      message.error(error.response.data.message);
  }
  return Promise.reject(error);
};

//添加响应拦截器
service.interceptors.response.use(res => {
  // 统一存储token
  if (res.data.code == 200) {
    // localStorage.setItem('token',res.data.token)
  }
  return res.data
}, err)

export default service
